<template>
	<view class="bgWhite plr-24 pt-20 pb-40 radius-16" @scroll="onScroll">
		<view class="">
			<view class="listClass">
				<view v-for="(item, index) in dataInfo.recommend" :key="index" class="itemClass pointer relative hidden"
					@click.stop="handleItem">
					<!-- <uv-image :src="item.imgUrl ? item.imgUrl: item.synthesisImg" 
					></uv-image> -->

					<view style="overflow: hidden;"
						@click="addOpen(`/pages/mine/veinManDetails?flag=hot3&user=`  +item.id)">
						<image :src="item.imgUrl ? item.imgUrl : item.synthesisImg" alt="Network Image"
							mode="aspectFill"
							:style="{ height: calculateHeight(item.height) + 'rpx', width: '100%' }" />
					</view>
					<view class="bgMinor5 flex pd-16">
						<view class="flex flex-1">
							<uv-image :src="item.avatar" width="32rpx" height="32rpx" shape="circle"></uv-image>
							<view class="size-15 ml-16 color-black3 line-hiding-1 flex-1">
								{{ item.userId_dictText }}
							</view>
						</view>
						<!-- 					@click="addOpen(`/pages/homepage/rehandling?tab=1&current=1&id=` + item.id)" -->
						<view class="flex" v-if="dataInfo.name">
							<uv-image @click="Trial(item)" src="/static/images/shiyong1.png" width="60rpx"
								height="30rpx" mode="scaleToFill"></uv-image>
						</view>
					</view>
				</view>
			</view>
			<view class=" mt-40" v-if=" dataInfo.recommend.length== 0 " style="width: 100%;">
				<view
					style="font-size: 30rpx;width: 100%;text-align: center;  color: rgb(204, 204, 204);height: 25vh;display: flex;align-items: center;justify-content: center;width: 100%;">
					暂 无 数 据</view>
			</view>
			<view v-if="!dataInfo.hasMoreData"
				style="font-size: 30rpx;width: 100%;text-align: center;  color: rgb(204, 204, 204);height: 25vh;display: flex;align-items: center;justify-content: center;width: 100%;">
				没有更多数据了</view>
		</view>

		<uv-popup ref="popupUseRef" mode="center" :close-on-click-overlay="false" round="16rpx" safeAreaInsetTop
			closeable>
			<view class="pb-20">
				<view class="mxr">
					脉星人功能仅商家可以使用
				</view>
				<view class="cwsj" @click="cwsj">
					成为商家
				</view>
			</view>
		</uv-popup>

	</view>
</template>

<script setup lang="ts">
	import { onMounted, reactive, ref, watch } from 'vue';
	import { baseURL } from '@/utils/config.ts';
	import { getWindowHeight } from '@/pages/util/getHeight';
	import { onLoad, onReachBottom, onShow, onHide, onPageScroll } from '@dcloudio/uni-app';
	import { addOpen, loggedIn, addOpenTab } from '@/pages/util/hooks';
	import useLoginStore from '@/pinia-store/userInfoStore';
	import { get, post } from '@/utils/request';

	const { name, key } = withDefaults(
		defineProps<{
			name : String;
			key : any
			// info: Array<T>;
		}>(),
		{
			name: () => '',
			key: () => '',
			// info: () => null // 复杂数据类型使用函数返回的方式
		}
	);
	watch(
		() => key,
		(newValue, oldValue) => {
			console.log('key 的值发生了变化，旧值:', oldValue, '新值:', newValue);
			// 在这里可以添加你需要的处理逻辑
		},
		{
			immediate: false, // 是否在组件挂载时立即执行一次回调，这里设置为 false 表示不立即执行
			deep: false // 是否深度监听，对于非对象或数组类型，通常不需要深度监听
		}
	);
	const useLogin = useLoginStore();
	const popupUseRef = ref(null);
	// console.log('useLoginuseLogin',useLogin);
	/** @name 数据 */
	const dataInfo = reactive({
		username: '',
		password: '',
		captcha: '',
		title: '初始标题',
		name: 1,
		hasMoreData: true,
		isLoading: false,
		currentPage: 1,
		list: [],
		recommend: [],
		total: 0,
		pages: 0,
		pageNo: 1,
		msg: '',

	});
	const listFun = async (val) => {
		// 热门展示
		if (val == 'del') {
			dataInfo.recommend = []
		}

		try {
			const response = await get<{
				pageNo : Number,
				pageSize : Number,
				type : Number
			}>('/maixing/getList', { pageNo: dataInfo.pageNo, pageSize: 20, type: 0 });
			if (response.code == 200) {

				dataInfo.pages = response.result.pages
				dataInfo.total = response.result.total
				dataInfo.recommend = [...dataInfo.recommend, ...response.result.records]
				console.log(dataInfo.recommend)
			}

		} catch (error) {
			console.error(error);
		}
	};
	const recommendFun = async () => {
		// 推荐

		try {
			const response = await get<{
				pageNo : Number,
				pageSize : Number,
				type : Number
			}>('material/getList', { pageNo: dataInfo.pageNo, pageSize: 10, type: 1 });
			if (response.code == 200) {
				dataInfo.pages = response.result.pages
				dataInfo.total = response.result.total
				dataInfo.recommend = [...dataInfo.recommend, ...response.result.records]
			}
		} catch (error) {
			console.error(error);
		}
	};
	function modifyImgUrls(records) {
		return records.map(record => {
			const newRecord = { ...record };
			// newRecord.imgUrl = baseConfig.baseURL + 'preview/' + record.imgUrl;
			return newRecord;
		});
	}
	// 我的
	const maixinggetList = async () => {
		// 推荐

		try {
			const response = await get<{
				pageNo : Number,
				pageSize : Number,
				type : Number
			}>('maixing/getList', { pageNo: dataInfo.pageNo, pageSize: 10, type: 1 });
			if (response.code == 200) {

				dataInfo.pages = response.result.pages
				dataInfo.total = response.result.total
				dataInfo.recommend = [...dataInfo.recommend, ...response.result.records]

				dataInfo.recommend = modifyImgUrls(dataInfo.recommend)
			}

		} catch (error) {
			console.error(error);
		}
	};
	const ToLoweOnScrollr = () => {
		if (!dataInfo.isLoading && dataInfo.hasMoreData) {
			console.log(dataInfo.pageNo + '----' + dataInfo.pages)

			if (dataInfo.pageNo < dataInfo.pages) {
				dataInfo.pageNo++;
				console.log(name)
				console.log('55556565')
				listFun('1')
				// if (name == 4) {
				// 	recommendFun()
				// } if (name== 1) {
				// 	maixinggetList()
				// } if (name == 2) {
				// 	maixinggetList()
				// } if (name == 3) {
				// 	maixinggetList()
				// }
			} else {
				dataInfo.hasMoreData = false
				setTimeout(() => {
					dataInfo.hasMoreData = true
				}, 800)
			}

			// this.fetchData();
		}
	}
	// 页面滚动到底部时触发
	onReachBottom(() => {



	})
	onPageScroll((res) => {
		// console.log('555959595')
		// console.log(res.scrollTop, '距离页面顶部距离'); //距离页面顶部距离
	})
	onHide(() => {
		// console.log('gundongtiao')
		// console.log(uni.pageScrollTo.value)
	})
	defineExpose({
		listFun,
		ToLoweOnScrollr,
	});
	onShow(() => {
		console.log(uni.getStorageSync('route'))
		if (uni.getStorageSync('route') != 'pages/mine/veinManDetails') {

			dataInfo.pageNo = 1
			dataInfo.recommend = []
			console.log(dataInfo.name)
			console.log('++-+--+')
			listFun('1')
		} else {
			setTimeout(() => {
				uni.setStorageSync('route', null);
			}, 1000)
		}

	})
	const childComp = ref(null)
	// onMounted(() => {
	// 	childComp.value?.childMethod();
	// })
	onLoad((options : any) => {
		dataInfo.recommend = []

		// setNavigationBarTitleFun(options)
	})

	const onScroll = (e) => {
		console.log(e.detail.scrollTop)
	};
	const setNavigationBarTitleFun = (options : any) => {
		dataInfo.msg = options.msg

		uni.setNavigationBarTitle({
			title: options.name == 1 ? "我的" : options.name == 2 ? "库" : options.name == 3 ? "收藏" : options.name == 4 ? "推荐" : options.name == 5 ? "热门展示" : name == '5' ? "广场" : ''
		});
		dataInfo.recommend = []
		dataInfo.name = name == '5' ? 5 : options.name

		listFun('1')

	}
	const Returntoupperlevel = async (item) => {
		// 推荐

		try {
			if (dataInfo.msg == '1') {
				console.log("左")
				console.log(item.imgUrl)
			} else {
				console.log("右")
				console.log(item.imgUrl)
			}

			const pages = getCurrentPages();
			const prevPage = pages[pages.length - 2];

			if (prevPage) {
				// 调用上一个页面的方法，传递 imgUrl
				if (prevPage.$vm) {
					prevPage.$vm.setImageUrl(item.imgUrl, dataInfo.msg);
				}
			}

			// 返回上一个页面
			uni.navigateBack({
				delta: 1
			});


		} catch (error) {
			console.error(error);
		}
	};
	const Trial = async (item : { isMember : any; imgUrl : any; }) => {
		console.log("============")
		try {
			// var isMember = JSON.parse(uni.getStorageSync('userData')).isMember;
			// var isMerchant = JSON.parse(uni.getStorageSync('userData')).isMerchant;
			// if((item.isMxr == 1 && isMerchant == 1) || (item.isMember == 1 && isMember == 1)){
			// 	uni.navigateTo({
			// 			url: `/pages/homepage/rehandling?tab=1&current=1&id=` + item.id, // 目标页面路径（需在pages.json注册）
			// 			success: () => console.log('跳转成功'),
			// 			fail: (err) => console.error('跳转失败', err)
			// 		})
			// }else if ((item.isMember ==1 && isMember!=1) || item.isMxr ==1 && isMerchant!=1){
			// 	 popupUseRef.value?.open();
			// }else{
			// uni.navigateTo({
			// 		url: `/pages/homepage/rehandling?tab=1&current=1&id=` + item.id, // 目标页面路径（需在pages.json注册）
			// 		success: () => console.log('跳转成功'),
			// 		fail: (err) => console.error('跳转失败', err)
			// 	})
			// }
			
			if (item.isMember == '1') {
				uni.navigateTo({
					url: `/pages/homepage/rehandling?tab=1&current=1&id=` + item.id, // 目标页面路径（需在pages.json注册）
					success: () => console.log('跳转成功'),
					fail: (err) => console.error('跳转失败', err)
				})
			} else {
				popupUseRef.value?.open();
			}
			// 	// uni.navigateTo({
			// 	//                url: `/pages/subscribeMember/index`, // 目标页面路径（需在pages.json注册）
			// 	//                success: () => console.log('跳转成功'),
			// 	//                fail: (err) => console.error('跳转失败', err)
			// 	//            })
			// 	// console.log("成为商家")
			// }

		} catch (error) {
			console.error(error);
		}
	}
	
	const cwsj =  async () => {
	
		console.log("============")
		try {
			popupUseRef.value?.close();
			uni.navigateTo({
			               url: `/pages/subscribeMember/index`, // 目标页面路径（需在pages.json注册）
			               success: () => console.log('跳转成功'),
			               fail: (err) => console.error('跳转失败', err)
			           })
			// console.log("成为商家")

		} catch (error) {
			console.error(error);
		}
	}
	
	
	/** @name xxx */
	function getUserInfo() { }

	/** @name 热门的选中事件 */
	async function handleItem() { }

	/** @name 动态计算高度 */
	function calculateHeight(height) {
		if (height > 2500) {
			return 450;
		} else if (height > 1500) {
			return height / 3;
		} else if (height < 600) {
			return height;
		} else {
			return height / 2;
		}
	}
</script>

<style scoped lang="scss">
	.listClass {
		column-count: 2;
		column-gap: 24rpx;
	}

	.itemClass {
		break-inside: avoid;
		margin-bottom: 24rpx;
		background: rgb(242, 242, 242);
		border-radius: 16rpx;
		overflow: hidden;
	}

	.mxr {
		width: 690rpx;
		box-sizing: border-box;
		padding: 0rpx 50rpx;
		box-sizing: border-box;
		font-weight: bold;
	}

	.cwsj {
		width: 300rpx;
		height: 60rpx;
		margin: 50rpx auto 0rpx;
		border-radius: 10rpx;
		line-height: 60rpx;
		text-align: center;
		color: #ffffff;
		background: linear-gradient(90deg, rgb(255, 165, 13), rgb(255, 1, 82));
	}
</style>